package com.yztstudy.Listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yztstudy.document.ProductDocument;
import com.yztstudy.entity.Product;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 消息队列的监听
 */

@Component
public class RabbitMQListener {

    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * TODO 监听并插入数据的方法
     * @param product 产品
     */
    @RabbitListener(bindings = {@QueueBinding(value = @Queue(name = "insert.queue"), exchange = @Exchange("topic.ex"), key = "product.insert")})
    public void insert(Product product)
    {
        // TODO 1.指定插入类型
        IndexRequest indexRequest = new IndexRequest("product");
        indexRequest.id(product.getProductId().toString());

        // TODO 2.准备插入的数据
        ProductDocument productDocument = new ProductDocument(product);

        // TODO 3.执行插入操作
        ObjectMapper objectMapper = new ObjectMapper();
        String objectJSON = null;
        try {
            objectJSON = objectMapper.writeValueAsString(productDocument);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        indexRequest.source(objectJSON, XContentType.JSON);
        try {
            restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * TODO 监听并删除数据的方法
     * @param productId 商品的主键
     */
    @RabbitListener(bindings = {@QueueBinding(value = @Queue(name = "remove.queue"), exchange = @Exchange("topic.ex"), key = "product.remove")})
    public void remove(Integer productId)
    {
        // TODO 1.创建删除对象
        DeleteRequest deleteRequest = new DeleteRequest("product");
        deleteRequest.id(productId.toString());

        // TODO 2.客户端发送请求,执行删除
        try {
            restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
